/*
 * 按下左键处理
 */
document.onmousedown = function (event) {
	clearDownListDiv(event);
}; 

// JavaScript Document
var timeObj = null;
var dlInnerHTML = "";
//如果鼠标在autoFill范围外点击且autoFill打开，那么关闭autoFill
function clearDownListDiv(event) {
	event = event || window.event;
	var div = document.getElementById("downList");
	var sousuotiao = document.getElementById("query");
	if (div == null || sousuotiao == null) {
		return;
	};
	var sousuotiaoHeight = $(sousuotiao).height();
	var divLeft = $(div).offset().left;
	var divTop = $(div).offset().top;
	var divRight = divLeft + $(div).width();
	var divBottom = divTop + $(div).height();
	var mouseX = event.pageX ? event.pageX : event.clientX + document.body.scrollLeft - document.body.clientLeft;
	var mouseY = event.pageY ? event.pageY : event.clientY + document.body.scrollTop - document.body.clientTop;
	if (div.style.display != "none") {
		if (mouseX < divLeft || mouseX > divRight || mouseY < (divTop - sousuotiaoHeight) || mouseY > divBottom) {
			showOrHiddenAuto(2);
		}
	}
}
/*
 * 获取autofill数据
 * @param eve 事件对象
 */
function getAutoFill(eve, baseUrl) {
    //上下左右和回车键时候，不做ajax调用
	var keyCode = eve.keyCode;
	if (keyCode == 40 || keyCode == 38 || keyCode == 37 || keyCode == 39 || keyCode == 13) {
		return false;
	}
	return sendAutofill("", baseUrl);
}
/*
 * 获取autofill数据
 */
var isRun = false;
function sendAutofill(keyWord, baseUrl) {
	var dl = document.getElementById("list");//列表
	var keyWordObj = document.getElementById("query");
	var keyWord = trim(keyWordObj.value);
	if (keyWord != "") {
		keyWord = getJsParams(keyWord);
		getAutoFillAjax(keyWord, baseUrl);
	} else {
		dl.innerHTML = "";
		showOrHiddenAuto(2);
	}
	return true;
}

function getAutoFillAjax(keyWord, baseUrl) {
	isRun = true;
	var url = baseUrl + "autofill.htm?collectionName=jiareno&keyWord=" + keyWord;
	if(isRun){
		$.ajax({
			type: "GET",
			url: url,
			data: "",
			dataType:"jsonp",  
			jsonp: 'jsoncallback',
			timeout: 5000,
			success: function (httpObj) {
				if (httpObj != "") {
					var html = "";
					$.each(httpObj, function(i, item){
						html += "<li keyword=\""+item.value+"\"><a onclick='seleKey(\""+item.value+"\");' onmouseover='over(\""+i+"\")' onmouseout='out(\""+i+"\")'><span class='result'>"+item.hl_value+"</span></a></li>";
						//html += "<li keyword=\""+item.value+"\"><a onclick='seleKey(\""+item.value+"\");' onmouseover='over(\""+i+"\")' onmouseout='out(\""+i+"\")'><span>"+item.hl_value+"</span></a></li>";
					});
					$("#list").html("");
					$("#list").html(html);
					showOrHiddenAuto(1);
				} else {
					showOrHiddenAuto(2);
				}
				isRun = false;
			}
		});
	}
}

/*
 * 显示或隐藏推荐区域
 * flg: 0 交替显示和隐藏
 *      1 显示
 *      2 隐藏
 */
function showOrHiddenAuto(flg) {
	var obj = document.getElementById("downList");
	if (flg == 0) {
		if (obj.style.display == "block") {
			obj.style.display = "none";
		} else {
			obj.style.display != "block";
			openAutofill();
		}
	} else {
		if (flg == 1) {
			if (null != obj) {
				obj.style.display = "block";
			}
		} else {
			if (flg == 2) {
				if (null != obj) {
					obj.style.display = "none";
				}
			}
		}
	}
}


/*
 * 按上下键，选择autofill列表的值
 * @param eve 事件对象
 */
function _selectBykeyEvent(eve) {
	var dl = document.getElementById("list");//列表
	var downObj = document.getElementById("downList");
	var qObj = document.getElementById("query");
	var hdnKeyTemp = document.getElementById("hdnKeyTemp");
	var hdnIndex = document.getElementById("hdnCurIndex");
	if (eve.keyCode == 40 && downObj.style.display == "block") {
    //按向上键时移动光标
		var a = dl.getElementsByTagName("a");
		if (a.length > 0) {
			if (hdnIndex.value == "") {
				a[0].style.backgroundColor = "#f2f2f2";
//				a[0].style.color = "#FFFFFF";
				qObj.value = a[0].parentNode.getAttribute("keyword");
				hdnIndex.value = 0;
			} else {
				if (hdnIndex.value < a.length - 1) {
					a[hdnIndex.value].style.backgroundColor = "#FFFFFF";
//					a[hdnIndex.value].style.color = "#3366CC";
					hdnIndex.value = parseInt(hdnIndex.value) + 1;
					a[hdnIndex.value].style.backgroundColor = "#f2f2f2";
//					a[hdnIndex.value].style.color = "#FFFFFF";
					qObj.value = a[hdnIndex.value].parentNode.getAttribute("keyword");
				} else {
					a[hdnIndex.value].style.backgroundColor = "#FFFFFF";
//					a[hdnIndex.value].style.color = "#3366CC";
					hdnIndex.value = "";
					qObj.value = hdnKeyTemp.value;
				}
			}
		}
	} else {
		if (eve.keyCode == 38 && downObj.style.display == "block") {
        //按向下键时移动光标
			var a = dl.getElementsByTagName("a");
			if (a.length > 0) {
				if (hdnIndex.value == "") {
					a[a.length - 1].style.backgroundColor = "#f2f2f2";
//					a[a.length - 1].style.color = "#FFFFFF";
					qObj.value = a[a.length - 1].parentNode.getAttribute("keyword");
					hdnIndex.value = a.length - 1;
				} else {
					if (hdnIndex.value > 0) {
						a[hdnIndex.value].style.backgroundColor = "#FFFFFF";
//						a[hdnIndex.value].style.color = "#3366CC";
						hdnIndex.value = parseInt(hdnIndex.value) - 1;
						a[hdnIndex.value].style.backgroundColor = "#f2f2f2";
//						a[hdnIndex.value].style.color = "#FFFFFF";
						qObj.value = a[hdnIndex.value].parentNode.getAttribute("keyword");
					} else {
						a[hdnIndex.value].style.backgroundColor = "#FFFFFF";
//						a[hdnIndex.value].style.color = "#3366CC";
						hdnIndex.value = "";
						qObj.value = hdnKeyTemp.value;
					}
				}
			}
		} else {
			if (eve.keyCode != 37 && eve.keyCode != 39 && eve.keyCode != 13) {
        //还原当前列表的索引和搜索关键字
				hdnIndex.value = "";
				hdnKeyTemp.value = qObj.value;
			}
		}
	}
	if (!eve) {
		eve = window.event;
	}//火狐中是 window.event
	if ((eve.keyCode || eve.which) == 13) {
		doSearchSubmit();
	}
}
/*
 * 清除按键选择的样式
 */
function clearSelected() {
	var dl = document.getElementById("list");//列表
	var hdnIndex = document.getElementById("hdnCurIndex");
	var a = dl.getElementsByTagName("a");
	if (a.length > 0 && hdnIndex.value != "") {
		a[hdnIndex.value].style.backgroundColor = "#FFFFFF";
//		a[hdnIndex.value].style.color = "#3366CC";
		hdnIndex.value = "";
	}
}
/*
 * 当前选择样式
 * @param index 当前索引
 */
function over(index) {
	clearSelected();
	var dl = document.getElementById("list");//列表
	var hdnIndex = document.getElementById("hdnCurIndex");
	var a = dl.getElementsByTagName("a");
	a[index].style.backgroundColor = "#f2f2f2";
//	a[index].style.color = "#FFFFFF";
	hdnIndex.value = index;
}
/*
 * 当前未被选中样式
 * @param index 当前索引
 */
function out(index) {
	var dl = document.getElementById("list");//列表
	var hdnIndex = document.getElementById("hdnCurIndex");
	var a = dl.getElementsByTagName("a");
	a[index].style.backgroundColor = "#FFFFFF";
//	a[index].style.color = "#3366CC";
}

/*
 * 选中autofill
 */
function seleKey(string) {
	var qObj = document.getElementById("query");
	qObj.value = string;
	showOrHiddenAuto(2);
	qObj.focus();
	doSearchSubmit();//提交表单
}

function isKeywordLegal(keyword){
	if(keyword == "%5C")
		return false;
	return true;
}

/*
 * 提交搜索
 */
function doSearchSubmit() {
	/*if (typeof (doBeforeSearch) != "undefined") {
		doBeforeSearch();
	}*/
	var target = document.getElementById("hdnTarget").value;
	var keyWordObj = document.getElementById("query");
	var keyWord = trim(keyWordObj.value);
	if (keyWord == "" || keyWord == "*") {
		keyWordObj.value = "";
		keyWordObj.focus();
		return;
	}
	while(true){
		if(keyWord.indexOf('_')>=0){
			keyWord = keyWord.replace("_"," ");
		}else{
			break;
		}
	}
	
/*while(true){
	if(keyWord.indexOf('\\')>=0){
		keyWord = keyWord.replace("\\"," ");
	}else{
		break;
	}
}*/
	
	/*
	while(true){
		if(keyWord.indexOf('<')>=0){
			keyWord = keyWord.replace("<","&lt;");
		}else{
			break;
		}
	}*/
	
	/*while(true){
		if(keyWord.indexOf('>')>=0){
			keyWord = keyWord.replace(">","&gt;");
		}else{
			break;
		}
	}*/
	
	/*while(true){
	if(keyWord.indexOf('\\')>=0){
		
		keyWord = keyWord.replace("\\","\\");
	}else{
		break;
	}
	}
	*/
	while(true){
		if(keyWord.indexOf('"')>=0){
			keyWord = keyWord.replace('"','&quot;');
		}else{
			break;
		}
	}
	
	if(keyWord.length>100){
		alert("关键词不能超过100个字符，请重新输入");
		return;
	}
	//appendHistoryCookie(keyWord);
	keyWord = encodeURIComponent(keyWord);
	while(true){
		if(keyWord.indexOf('%2F')>=0){
			keyWord = keyWord.replace("%2F","/");
		}else{
			break;
		}
	}
	var url = target.replace('%23keyword%23',keyWord);
	url = url.replace('#keyword#',keyWord);
	if(isKeywordLegal(keyWord)){
		goUrlByATag(url);
	}else{
		url = url.replace(keyWord,'').trim();
		url += "?keyWord=" + keyWord;
		goUrlByATag(url);
	}
	//隐藏下拉框
	$("#downList").hide();
}
/**
  * 根据target和collection提交搜索
  */
function goToTarget(target, collection) {
	var keyWord = $("#query").val();
	var searchTargetObj = document.getElementById("hdnTarget");
	var ajaxCollectionObj = document.getElementById("ajaxCollection");
	searchTargetObj.value = target;
	ajaxCollectionObj.value = collection;
	doSearchSubmit();
}
/**
  * 设置target和 collection
  */
function setTarget(target, collection) {
	var searchTargetObj = document.getElementById("hdnTarget");
	var ajaxCollectionObj = document.getElementById("ajaxCollection");
	searchTargetObj.value = target;
	ajaxCollectionObj.value = collection;
}
/*
 * 通过关键字检索
 */
function goToSearch(keyWord) {
	var keyWordObj = document.getElementById("query");
	keyWordObj.value = keyWord;
	$(".labelshow").hide();
	doSearchSubmit();
}
/**
 * 退回到分类搜索
 */
function backToCategory(collection, category) {
	var keyWord = trim(document.getElementById("lastSearchKeyword").value);
	$("#hdnTarget").val("suiSearch.htm");
	$("#hdnParams").val("&categoryValue=" + encodeURIComponent(category));
	goToSearch(keyWord);
}

// JavaScript Document
/*
 * 去掉字符串前后空格
 * @param keyWord 没转换前字符串
 * @return 去掉前后空格后的字符串
 */
function trim(keyWord) {
	var regex = /^\s*|\s*$/g;
	if(typeof(keyWord)!='undefined') {
		var trimstr = keyWord.replace(regex, "");
		return trimstr;
	} else {
		return "";
	}
}

function changeTargetLabel(target, collection) {
	var keyword = trim($("#query").val()); 
	var searchTargetObj = document.getElementById("hdnTarget");
	var ajaxCollectionObj = document.getElementById("ajaxCollection");
	searchTargetObj.value = target;
	ajaxCollectionObj.value = collection;
}

function replaceStr(str,str1,str2){
	while(true){
		if(str.indexOf(str1)>=0){
			str = str.replace(str1,str2);
		}else{
			return str;
		}
	}
}

function showHelp(){
	if(getCookies("showHelp")==null||getCookies("showHelp")==''){
		$("#needhelp").show();
	}
}

function closeHelp(){
	$("#needhelp").hide();
	setCookies("showHelp","NO");
}

function getJsParams(str) {
    var reg = /[']/g;
    var str = str.replace(reg, "\\'");
    str = str.replace(/\&/g, "&amp;");
    var reg = /["]/g;
    var str = str.replace(reg, "&quot;");
    return str;
}

function goUrlByATag(url) {
    var el = document.createElement("a");
    document.body.appendChild(el);
    el.href = url;
    el.target="_blank";
    if (el.click) {
        el.click();
    } else {
        try {
            var evt = document.createEvent("Event");
            evt.initEvent("click", true, true);
            el.dispatchEvent(evt);
        } catch (e) {
        }
    }
}